
var oTables = {}; 
var flag= false;

$(function() {
  
  $('#inputString').keyup(function() {
	 var inputString = $(this).val();
     if(inputString.length == 0) {
	   // Hide the suggestion box.
	   $('#suggestions').hide();
	   } else {
	     $.post("rpc.php", {queryString: ""+inputString+""}, function(data){
	       if(data.length >0) {
	         $('#suggestions').show();
	         $('#autoSuggestionsList').html(data);
	       }
    	   $.post("request.php", { query: ""+inputString+"" }, function(data) {
    		   $("input#inputString").val(inputString).attr("title",data);   		  
    		 });
	     }); //end of post
	   }
   });
   
   $("a.clickable").click(function(event){
       event.preventDefault();
       var inputString = $(this).attr('title');
       
       if (inputString.match(/\w+:\d+,\d+/)) {
    	   $("input#inputString").val(inputString);   	   
       } 
       else {
    	   $.post("request.php", { query: ""+inputString+"" }, function(data) {
    		   $("input#inputString").val(inputString).attr("title",data);   		  
    		 });
       }
   });
 

  $("#target").submit(function () {
      
   var res;
   /* SEARCH BY LOCATION */
   if($('#inputString').val().match(/(\d+|[xy]):(\d+)[,-](\d+)/i)) {
	   res = $('#inputString').val().match(/(\d+|[xy]):(\d+)[,-](\d+)/);
   } 
   /* SEARCH BY BAND */
   else if ($('#inputString').val().match(/^(\d+|[xy])([p|q])(\d*)([.]?)(\d*)$/i)) {
	   var band       = $('#inputString').val().match(/^(\d+|[xy])([p|q])(\d*)([.]?)(\d*)$/i);
	   var chromosome = band[1];
	   var escapeDot  = '\\.';
	   var id_band;
	   (band[4] == '.')? id_band = band[2]+band[3]+escapeDot+band[5] 
	                   : id_band = band[2]+band[3];

	   var request = "proxy.php?s=http://www.ensembl.org/das/Homo_sapiens.GRCh37.karyotype/features?segment="+chromosome;
	   $.ajax({
		   type: "POST",
		   url: request,
		   async: false,
		   success: function(data){
		     var start = $(data).find("#"+id_band).children("START").text();  	
		     var end   = $(data).find("#"+id_band).children("END").text();
		     var coord  = chromosome+':'+start+','+end;
		     res = coord.match(/(\w+):(\d+)[,-](\d+)/);   		    
		   }    	   
		 });
	  
   } else if ($('#inputString').attr('title').match(/(\w+):(\d+)[,-](\d+)/)){
	   res = $('#inputString').attr('title').match(/(\w+):(\d+)[,-](\d+)/);

   }  else {
	   alert('Unrecognized input, please try again.');
	   return false;
   }

   var chr       = res[1];
   var chr_start = res[2];
   var chr_end   = res[3];
   sessvars.karyoDas.conf.zoomConf = [chr,chr_start,chr_end]; 
   //sessvars.karyoDas.conf.userEntryPoints = [chr];
   //return false;
  });
  
  $('.source_link').live('click', function(){
	    jQuery.facebox({ div: '#add_source' });
	    return false;
   });
	  
  $('.add_source_form').live('submit', function() {
	  var source_name = $(this).find('input[name=name]').val();
	  var source_desc = $(this).find('input[name=desc]').val();
	  var source_url  = $(this).find('input[name=url]').val();
	  if( source_name && source_desc && source_url ) {
		var rowNo = $('#sources tbody tr').length + 1;

		$('#sources > tbody:last').append('<tr id="source_'+rowNo+'" title="'+source_name+'">'
				+ '<td><select class="representation_type"><option value="track">track</option><option value="mark">mark</option></select></td>'
				+ '<td><select class="selected_view"><option value="zoom">zoom</option><option value="chromosome">chromosome</option><option value="karyotype">karyotype</option></select></td>'
				+ '<td class="name">'+source_name+'</td>'
				+ '<td class="desc">'+source_desc+'</td>'
				+ '<td><input class="url" type="hidden" value="'+source_url+'"><a class="delete" rel="#source_'+rowNo+'" title="delete source_'+rowNo+'" href="."><img src="img/delete_cross.png" title="Delete"></a></td>'
				+'</tr>');

	    jQuery.facebox.close();
	    populate_sources();
	    return false;
	  }

	  /*else if ($(this).find('input[name=file]').val()) {
	     var request = "upload.php";
		 $.ajax({
			   type: "POST",
			   url: request,
			   async: false,
			   success: function(data){		   
  		         alert(data.);
			   },
			   dataType: "json"       
		   });
		   return false;	   
      }  */
	  else {
        alert('At least one of the fields is empty.\nPlease fill it in and try again.');
        return false;
      }
  });
  $('form a.submit').live('click', function(){
	    $(this).parents('form').submit(); 
	    return false;
  });
	  
  /*
   * Data Table
   */  
  
  $('.data-table').livequery(function(){
    id = $(this).attr('id');
    var options = {
      bAutoWidth: false,
      bStateSave: false,
      sPaginationType: 'full_numbers',
      sDom: '<"top" if>t<"bottom"lp>',
      fnInitComplete: function () {
        var $filter = $('div.dataTables_filter[rel=' + $(this).attr('id') + ']');
        if ($filter.length) {
          $filter.replaceWith( $(this).parents('.dataTables_wrapper').find('.dataTables_filter').detach() );
        }
        
        //$(this).parents('.cb').show();

        var bottomButtons = $(this).parents('div.dataTables_wrapper').siblings('.data-table-bottom-buttons').detach();
        $(this).siblings('div.bottom').append(bottomButtons);
        $(this).parents('div.dataTables_wrapper').siblings('.loader').hide();
        $(this).show();
      },
      fnDrawCallback: function(oSettings) {
        if (Math.ceil((oSettings.fnRecordsDisplay()) / oSettings._iDisplayLength) > 1)  {
          $('#' + oSettings.sTableId + '_paginate').show();
        } else {
          $('#' + oSettings.sTableId + '_paginate').hide();
        }
      },
      oLanguage: {
        sZeroRecords: "Nothing found",
        sInfo: "_START_ to _END_ of _TOTAL_ entries",
        sSearch: '',
        sLengthMenu: "_MENU_ per page"
      }
    };
    
    function parseOption(val){
      var rtn;
      try {
        rtn = JSON.parse(val);
      } catch(e) {
        rtn = parseInt(val, 10);
        if (isNaN(rtn)) { rtn = val; }
      }
      return rtn;
    }

    $(this).siblings('input.data-table-options').each(function(){
      options[this.name] = parseOption(this.value);
    });

    oTable = $(this).dataTable(options);
    oTables[id] = oTable;
  }); 

  $('.dataTables_filter>input').live('keyup', function(){
    if ($(this).val().length) {
      if (!$(this).hasClass('active')) {
        $(this).addClass('active');
        $(this).parent('div.dataTables_filter').append('<img height="17" src="/i/blank.gif" title="cancel" style="position: absolute; z-index: 100; margin-top: -2px; margin-left: -20px; cursor: pointer;">');
      }
    } else {
      $(this).siblings('img').remove();
      $(this).removeClass('active');
    }
  });

  $('.dataTables_filter img').live('click', function(){
    $(this).siblings('input').val('').trigger('keyup');
  });
    
  $('table a.delete').livequery('click', function(){
    var $a = $(this);
    var $table = $(this).parents('table');
    //if (confirm('Are you sure you want to ' + $(this).attr('title') + '?')) {
        if ($table.hasClass('data-table')) {
            oTables[$table.attr('id')].fnDeleteRow( $( $a.attr('rel') )[0] );
            populate_sources();
          }    
      
    //}
    return false;
  });    

  $('table a.details').livequery('click', function(){
    var $table = $(this).parents('table');
    var nTr    = this.parentNode.parentNode;
    if (this.title.match('Close Details')) {
      oTables[$table.attr('id')].fnClose( nTr );
      this.title = 'Open Details';
    } else {
      oTables[$table.attr('id')].fnOpen( nTr, '<div class="ajax nocache" style="border-bottom: 1px dotted #bcc5cc;" rel="' + $(this).attr('href') + '"><div class="loader"><img src="/i/icons/ajax_loader.gif"></div></div>', 'details' );
      this.title = 'Close Details';
    }
    return false;
  });    
  
  $('table.choosable tbody tr').livequery('click', function(event){
	    if (event.target.nodeName != 'INPUT') {
	      var radio = $(this).find('input[type=radio]');
	      radio.attr('checked', !radio.is('checked')).trigger('change');
	    }
  });
  $('table.highlightable tbody tr').live('mouseover', function(){
    $(this).children('td').css("background-color","#BCC5CC");
  });
  $('table.highlightable tbody tr').live('mouseout', function(){
    $(this).children('td').css("background-color","");
  });
	  
});

function fill(thisValue,thisTitle) {
	
    $('#inputString').val(thisValue).attr('title',thisTitle);
   $('#suggestions').hide();
}

function populate_sources () {
	
	sessvars.karyoDas.conf.sources = new Array();
    $('#sources tbody tr').each(function() {
        var source            = new Object();
        source.id             = $(this).find(".name").html();
        source.name           = $(this).find(".name").html();
        source.label          = [$(this).find(".name").html()];
        source.description    = $(this).find(".desc").html();
        source.url            = $(this).find(".url").val();
        source.representation = $(this).find(".representation_type option:selected").text();
        source.panel          = $(this).find(".selected_view option:selected").text();  
        source.ntLimit        = 17000000;
        source.types          = [];
        sessvars.karyoDas.conf.sources.push(source);       
     });
}





 

 
  
